<template>
  <div class="fileupload-container">
    <el-upload
      class="upload-demo"
      drag
      :action="uploadUrl"
      :file-list="fileList"
      :limit="limit"
      :show-file-list="false"
      :accept="accept"
      :headers="headers"
      :before-upload="handleBeforeUpload"
      :on-success="handleOnSuccess"
      :on-exceed="handleOnExceed"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">{{accept ?`只能上传${accept}文件`:'接收任意类型文件'}}</div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="index"
        class="el-upload-list__item is-success"
        v-for="(file,index) in fileList"
        :tabindex="index"
      >
        <a class="el-upload-list__item-name">
          <el-image v-if="preview" style="width: 50px; height: 50px" :src="file.url"></el-image>
          <i v-else class="el-icon-document"></i>
          <span>{{file.name}}</span>
        </a>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-circle-check"></i>
        </label>
        <i class="el-icon-close" @click="handleBeforeRemove(file)"></i>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  props: {
    value: {
      type: Array
    },
    multiple: {
      type: Boolean,
      default: false
    },
    preview: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 10
    },
    mediaType: {
      type: Array,
      default: function() {
        return [];
      }
    },
    url: {
      typ: String,
      default: ""
    }
  },
  data() {
    return {
      fileList: [],
      headers: {
        Authorization: getToken()
      }
    };
  },
  computed: {
    accept() {
      return this.mediaType.join("/");
    },
    uploadUrl() {
      return this.url
        ? process.env.VUE_APP_BASE_API + this.url
        : "https://jsonplaceholder.typicode.com/posts/";
    }
  },
  methods: {
    // 上传之前的处理
    handleBeforeUpload(file) {
      if (!this.multiple && this.fileList.length === 1) {
        this.$message({
          type: "warning",
          message: "只支持单文件上传"
        });
        return false;
      }

      // 校检文件类型
      if (this.mediaType.length > 0) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.mediaType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$message({
            type: "warning",
            message: `文件格式不正确, 请上传【${this.mediaType.join(
              ","
            )}】格式文件!`
          });
          return false;
        }
      }

      // 校检文件大小
      // if (this.fileSize) {
      //   const isLt = file.size / 1024 / 1024 < this.fileSize;
      //   if (!isLt) {
      //     this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
      //     return false;
      //   }
      // }

      return true;
    },
    // 上传成功之后的处理
    handleOnSuccess(response, file, fileList) {
      if (response.code === 200) {
        const obj = {
          uid: file.uid,
          name: file.name,
          url: URL.createObjectURL(file.raw), // 创建缩略图（blob:http://localhost:9528/9ce5b6ed-81a7-43a5-b429-15f6babc8ff1）
          data: response.data
        };
        this.fileList.push(obj);
        this.$emit("input", this.fileList);
      } else {
        this.$message({
          type: "error",
          message: response.msg
        });
      }
    },
    // 上传失败之后的处理
    handleUploadError(err) {
      this.$message({
        type: "error",
        message: `上传文件失败，请重试`
      });
    },
    // 删除列表中的文件
    handleBeforeRemove(file) {
      this.fileList.splice(
        this.fileList.findIndex(item => item.uid === file.uid),
        1
      );
      this.$emit("input", this.fileList);
    },
    // 文件超出个数限制时执行
    handleOnExceed(files, fileList) {
      this.$message({
        type: "warning",
        message: `允许上传的个数限制【${this.limit}个】`
      });
    },
    // 自定义请求
    handleHttpRequest(data) {
      console.log(data);
    }
  }
};
</script>

<style lang="scss">
.fileupload {
  &-container {
  }
}
</style>